package top.api.timer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.api.Constants.SystemConstants;
import top.api.domain.entity.Article;
import top.api.service.ArticleService;
import top.api.utils.RedisCache;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class UpdateViewCountTimer {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    /**
     * 将redis中的文章访问量拷贝到数据库
     * 每隔 5 分钟
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateViewCount(){
        // 获取redis数据
        Map<String, Integer> cacheMap = redisCache.getCacheMap(SystemConstants.REDIS_VIEWCOUNT_KEY);
        // 将map转换到list
        List<Article> articles = new ArrayList<>();
        Article article;
        for (Map.Entry<String, Integer> viewCount : cacheMap.entrySet()) {
            article = new Article(Long.parseLong(viewCount.getKey()),viewCount.getValue());
            articles.add(article);
        }
        // 拷贝到数据库
        articleService.updateBatchById(articles);

        log.info("updateViewCountTimer: {}","运行成功!");
    }
}
